<?php
function mobile_service_plant_info_list($parameters)
{
    global $user;
    $user_info = _get_user_info($user->uid);
    $start = $parameters['page_count'] * variable_get("list_page_item_number", 5);
    $query = db_select('plant_info', 'PI');
    $query->join('farmer', 'F', 'F.farmer_id=PI.farmer_id');
    $query->join('plant', 'P', 'P.plant_id=PI.plant_id');
    $query->join('addr', 'A', 'F.addr_id=A.addr_id');

    if (get_user_role_name($user->uid) === '农户') {
        $datestr = '';
        if (!empty($form_state['values']['year'])) {//查询条件
            if ($form_state['values']['year']) {
                $datestr .= $form_state['values']['year'] . '-';
            }
        }
        if ($datestr) {
            $query->condition('PI.sow_date', db_like($datestr) . '%', 'LIKE');
        }
        $query->condition('PI.farmer_id', $user->uid);

    } else {
        if(!user_access('view all plant_info') && user_access('view own plant_info')){
            $query->condition('PI.author_uid',$user->uid, '=');
        }
        //地址级别查询
        if (!empty($form_state['values']['village'])) {//乡镇级
            $query->condition('A.village_id', $form_state['values']['village'], '=');
        } elseif (!empty($form_state['values']['town'])) {//乡镇级
            $query->condition('A.town_id', $form_state['values']['town'], '=');
        } elseif (!empty($form_state['values']['county'])) {//县级
            $query->condition('A.county_id', $form_state['values']['county'], '=');
        } elseif (!empty($form_state['values']['city'])) {//市级
            $query->condition('A.city_id', $form_state['values']['city'], '=');
        } elseif (!empty($form_state['values']['province'])) {//省级
            $query->condition('A.province_id', $form_state['values']['province'], '=');
        }
        if (!empty($form_state['values']['address_fuzzy'])) {
            $query->condition('A.name', '%' . db_like($form_state['values']['address_fuzzy']) . '%', 'LIKE');
        }
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('PI.farmer_id', $form_state['values']['farmer']);
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('PI.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('PI.farmer_id', $form_state['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $form_state['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('PI.farmer_id', $form_state['values']['farmer_id'], '=');
        }
    }

    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('PI.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('PI.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('PI.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('PI.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }

    $query->fields('PI');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    $query->addField('P', 'plant_name');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'farmer_id');
    $query->orderBy('PI.plant_info_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('PI.plant_info_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);

    $results = $query->execute();
    $results_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $results_list[] = $result;
        }
    }
    return  ["data"=>$results_list];
}
function plant_info_add_validate( &$parameters) {
    $validata_error = '';
   
    return $validata_error;
}

function mobile_service_plant_info_add($parameters)
{
//    $validate_result = plant_info_add_validate($parameters);
//    if(!empty($validate_result)){
//        $result_option = (object)["option" => 0,"error"=>$validate_result];
//        return $result_option;
//    }
    $module_name="plant_info";
    global $user;
    $id = !empty($parameters['plant_info_id'])?$parameters['plant_info_id']:'';
    $transaction = db_transaction();
    try {
        if (empty($id)) {
            if(!user_access('add '.$module_name)){
                return ['option'=>0,'errorNum'=>3];
            }
            $nid = db_insert('plant_info')
                ->fields(array(
                    'farmer_id' => $parameters['farmer_id'],
                    'plant_id' => $parameters['plant_id'],
                    'sow_date' => $parameters['sow_date'],
                    'harvest_date' => $parameters['harvest_date'],
                    'seed' => $parameters['seed'],
                    'irrigation' => $parameters['irrigation'],
                    'plant_area' => _empty_2_zero($parameters['plant_area']),
                    'plant_space' => _empty_2_zero($parameters['plant_space']),
                    'row_space' => _empty_2_zero($parameters['row_space']),
                    'general_yield' => _empty_2_zero($parameters['general_yield']),
                    'other_yield' => _empty_2_zero($parameters['other_yield']),
                    'seed_cost' => _empty_2_zero($parameters['seed_cost']),
                    'fertilizer_cost' => _empty_2_zero($parameters['fertilizer_cost']),
                    'pesticide_cost' => _empty_2_zero($parameters['pesticide_cost']),
                    'machinery_cost' => _empty_2_zero($parameters['machinery_cost']),
                    'others_cost' => _empty_2_zero($parameters['others_cost']),
                    'comments' => $parameters['comments'],
                    'author_uid' => $user->uid,
                    'timestamp' => time(),
                ))
                ->execute();
            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                $fid = db_insert('fertilization_info')
                    ->fields(array(
                        'plant_info_id' => $nid,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        } else {
            if(!mobile_user_edit_access($module_name,$module_name.'_id',$id,'edit own '.$module_name,'edit all '.$module_name)){
                return ['option'=>0,'errorNum'=>3];
            }
            $nid = db_update('plant_info')
                ->fields(array(
                    'farmer_id' => $parameters['farmer_id'],
                    'plant_id' => $parameters['plant_id'],
                    'sow_date' => $parameters['sow_date'],
                    'harvest_date' => $parameters['harvest_date'],
                    'seed' => $parameters['seed'],
                    'irrigation' => $parameters['irrigation'],
                    'plant_area' => _empty_2_zero($parameters['plant_area']),
                    'plant_space' => _empty_2_zero($parameters['plant_space']),
                    'row_space' => _empty_2_zero($parameters['row_space']),
                    'general_yield' => _empty_2_zero($parameters['general_yield']),
                    'other_yield' => _empty_2_zero($parameters['other_yield']),
                    'seed_cost' => _empty_2_zero($parameters['seed_cost']),
                    'fertilizer_cost' => _empty_2_zero($parameters['fertilizer_cost']),
                    'pesticide_cost' => _empty_2_zero($parameters['pesticide_cost']),
                    'machinery_cost' => _empty_2_zero($parameters['machinery_cost']),
                    'others_cost' => _empty_2_zero($parameters['others_cost']),
                    'comments' => $parameters['comments'],
                    'timestamp' => time(),
                ))
                ->condition('plant_info_id', $id, '=')
                ->execute();
            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                if (isset($fertilizer['id']) && !empty($fertilizer['id'])) {
                    continue;
                }
                $fid = db_insert('fertilization_info')
                    ->fields(array(
                        'plant_info_id' => $id,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        }
    } catch (Exception $e) {
        $transaction->rollback();
        $result_option = (object)["option" => 0,"error"=>$e->getMessage()];
        return $result_option;
    }
}
